import {
  Form,
  Button,
  Card,
  Breadcrumb,
  Radio,
  Select,
  DatePicker,
  Table,
  Space,
  Tag,
  Image,
  Modal,
} from "antd"
import { Link } from "react-router-dom"
import styles from "./index.module.scss"
import { EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { useChannels } from "@/utils/customHooks"
import { useEffect, useRef } from "react"
import { getArticles, delArticle } from "@/store/actions/article"
import { useDispatch, useSelector } from "react-redux"
import defaultImg from "@/assets/error.png"
import { useHistory } from "react-router-dom"
const statusLabel = [
  { text: "草稿", color: "default" },
  { text: "待审核", color: "blue" },
  { text: "审核通过", color: "green" },
  { text: "审核拒绝", color: "red" },
]

const Article = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const paramsRef = useRef({
    page: 1,
    per_page: 10,
    channel_id: undefined,
    status: undefined,
    begin_pubdate: undefined,
    end_pubdate: undefined,
  }) // 存储参数对象的
  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      key: "cover",
      render: (cover) => {
        let imgUrl = defaultImg
        if (cover?.images?.length) {
          // 返回一张真实的图片
          imgUrl = cover.images[0]
        }
        // 返回默认图片
        return (
          <Image
            src={imgUrl}
            style={{ objectFit: "cover" }}
            width={200}
            height={120}
          ></Image>
        )
      },
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        return (
          <Tag color={statusLabel[status].color}>
            {statusLabel[status].text}
          </Tag>
        )
      },
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
      key: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
      key: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
      key: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
      key: "like_count",
    },
    {
      title: "操作",
      key: "action",
      render: (_, row) => (
        <Space size="middle">
          <Button
            onClick={() => history.push("/home/publish/" + row.id)}
            type="link"
            icon={<EditOutlined />}
          />
          <Button
            onClick={() => {
              Modal.confirm({
                title: "您是否确认删除该文章？",
                onOk: async () => {
                  // 调用删除接口
                  await dispatch(delArticle(row.id)) // 调用删除action
                  // 重新加载数据
                  dispatch(getArticles(paramsRef.current))
                },
              })
            }}
            danger
            type="link"
            icon={<DeleteOutlined />}
          />
        </Space>
      ),
    },
  ]
  const channels = useChannels()

  const { results, per_page, page, total_count } = useSelector(
    (state) => state.article
  )
  useEffect(() => {
    dispatch(getArticles(paramsRef.current))
  }, [dispatch])

  const onFinish = (values) => {
    paramsRef.current.status = values.status
    paramsRef.current.channel_id = values.channel_id
    if (values.dateArr) {
      paramsRef.current.begin_pubdate = values.dateArr[0].format(
        "YYYY-MM-DD HH:mm:ss"
      )
      paramsRef.current.end_pubdate = values.dateArr[1].format(
        "YYYY-MM-DD HH:mm:ss"
      )
    } else {
      paramsRef.current.begin_pubdate = undefined
      paramsRef.current.end_pubdate = undefined
    }
    paramsRef.current.page = 1 // 改变了筛选条件 要将页码重置为1
    // 再次发起请求
    dispatch(getArticles(paramsRef.current))
  }

  const onPageChange = (page, pageSize) => {
    // 要加载的页码和每页条数
    // paramsRef会保留我们的筛选条件
    paramsRef.current.page = page
    paramsRef.current.per_page = pageSize
    dispatch(getArticles(paramsRef.current)) // 请求对应页码的数据
  }

  return (
    <div className={styles.root}>
      <Card
        title={
          // 面包屑
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单 */}
        <Form onFinish={onFinish}>
          <Form.Item name="status" label="状态：">
            <Radio.Group>
              <Radio value={undefined}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="channel_id" label="频道：">
            <Select style={{ width: 288 }}>
              {channels.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="日期：" name="dateArr">
            <DatePicker.RangePicker></DatePicker.RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card
        style={{ marginTop: 24 }}
        title={`根据筛选条件共查询到 ${total_count} 条结果`}
      >
        <Table
          pagination={{
            current: page,
            pageSize: per_page,
            total: total_count,
            onChange: onPageChange,
          }}
          rowKey="id"
          columns={columns}
          dataSource={results}
        ></Table>
      </Card>
    </div>
  )
}

export default Article
